import { NextFunction, Request, Response } from 'express';
import { deToken, resolveToken } from '../../utils/common';
import { error } from '../../utils/resp';
class Auth {
    /**
     * 校验是否登录了
     * @param req 
     * @param res 
     */
    vertify(req: Request, res: Response, next: NextFunction) {
        // 从响应头中获取到token
        let token = req.headers.authorization; 
        // 没有token
        if (!token) { 
            next({ msg: '还没有登录哦, 请先登录才能执行此操作', code: 401 })
        } else {
            // 去掉bearer
            token = resolveToken(token);

            const isPass = deToken(token);
            if (!isPass) {
                // token无效
                error(res, { msg: '登录失效' })
            } else {
                // token有效, 交给下一个函数处理
                (req as any).user = isPass;
                next();
            }
        }
    }
}

export default new Auth;